import axios from 'axios'
// 根据环境不同引入不同api地址
import {
	baseUrl
} from '@/util/config.js'
// create an axios instance
import axiosAdapterUniapp from 'axios-adapter-uniapp'
const service = axios.create({
	baseURL: baseUrl, // url = base api url + request url
	adapter: axiosAdapterUniapp,
	timeout: 50000, // request timeout
})

// request拦截器 request interceptor
service.interceptors.request.use(
	(config) => {
		console.log(config);
		// 修改提交header方式
		config.headers['Content-Type'] = 'multipart/form-data'
		let token = uni.getStorageSync('X-Access-Token')
		if (token) {
			config.headers['Authorization'] = 'Bearer ' + token
		}
		return config
	},
	(error) => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	},
)
// respone拦截器
service.interceptors.response.use((response) => {
	const res = response.data
	if (res.code && res.code !== 200) {
		// 登录超时,重新登录
		if (res.code == 401) {
			uni.showToast(res.msg)
			uni.clearStorageSync();
			uni.navigateTo({
				url: '/pages/index/index',
			})
		} else if (res.code === 500) {
			uni.showToast({
				title: res.msg
			})
		}
		return Promise.reject(res || 'error')
	} else {
		return Promise.resolve(res)
	}
})

export default service